<?php

namespace app\api\controller\homepage;

use app\admin\model\member\Account;
use app\admin\model\member\ActivityCollect;
use app\admin\model\vactivities\Ticket;
use app\common\controller\Api;
use app\common\library\Iden;

use think\Db;

// 允许跨域
header('Access-Control-Allow-Origin:*');//允许跨域

/**
 * 个人中心
 * 个人收藏页
 */
class Collect extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    protected $catemodel = null;
    protected $tagsmodel = null;
    protected $actmodel = null;
    protected $actpmodel = null;
    protected $ticket_model = null;
    protected $api_act = null;
    protected $fmodel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\member\ActivityCollect;
        $this->actmodel = new \app\admin\model\vactivities\Activity;
        $this->catemodel = new \app\admin\model\superdata\Activitycategory;
        $this->tagsmodel = new \app\admin\model\superdata\Activitytags;
        $this->ticket_model = new \app\admin\model\vactivities\Ticket;
        $this->api_act = new \app\api\controller\activity\Activity;
    }




     /**
     * @desc 个人收藏的活动或系列列表页
     * @param $uid
     * */
    public function list(){
        $uInfo = $this->auth->getUserInfo();
        if(empty($uInfo)){//未登录
            $this->error(__('Please login first'), null, 401);
        }
        $admin_id = Iden::decrypt($uInfo['id']);
        if(empty($admin_id)){
            $this->error(__('获取用户参数出错'));
        }
        //$admin_id = 31896;
        $map['uid'] = intval($admin_id);
        $map['state'] = 1;
        $per_page = $this->request->get('per_page', 1);
        $limit  = (int)$this->request->get('limit', 20);
        $offset = ($per_page - 1) * $limit;
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        $list = $this->model
            ->with(['activity'])
            ->where($map)
            ->order('ctime DESC')
            ->limit($offset, $limit);
        $list = $list->select();
        $total = count($list);
        foreach ($list as $k=>$row) {
            $row->visible(['id','name','thumb','createTime','startTime','isticket','duration','uid','tags',
                'category','nickname','avatar','introduction','isseries','iscollect','price_min','price_max']);
            $row->getRelation('activity')->visible(['id','name','thumb','createTime','startTime','isticket','duration','series_id']);
            $tlist = $this->ticket_model->getTicketList($row['activity']['id'],Ticket::TICKET_TYPE_2,$row['activity']['admin_id']);

            if($tlist){
                $price = $this->max_min($tlist);
            }

            $list[$k]['id'] = Iden::encrypt($row['activity']['id']);
            $list[$k]['name'] = $row['activity']['name'];
            $list[$k]['price_min'] = isset($price) && !empty($price['min']) ? $price['min']:0;
            $list[$k]['price_max'] = isset($price) && !empty($price['max']) ? $price['max']:0;

            $list[$k]['isticket'] = $row['activity']['isticket'];
            $list[$k]['duration'] = s_to_hs($row['activity']['duration']);
            $list[$k]['startTime'] = date('Y-m-d H:i:s',$row['activity']['startTime']);

            if($row['activity']['thumb']){
                $thumbArr = explode(',',$row['activity']['thumb']);
                $list[$k]['thumb'] = !empty($thumbArr) ? $thumbArr:'';
            }

            $list[$k]['uid'] = Iden::encrypt($row['activity']['admin_id']);
            $list[$k]['tags'] = $this->tagsmodel->getTagsNameById($row['activity']['tags']);
            $list[$k]['category'] = $this->catemodel->getcateNameById($row['activity']['category']);
            $list[$k]['isseries'] = isset($row['activity']['series_id']) && ($row['activity']['series_id'] > 0) ? 1:0;
            $list[$k]['iscollect'] = $this->api_act->Iscollect($row['activity']['id']);//是否已收藏

            $uInfo = Account::getUsrInfoById($row['activity']['admin_id']);
            if($uInfo){
                $list[$k]['nickname'] = !empty($uInfo['nickname']) ? $uInfo['nickname']:'';
                $list[$k]['avatar'] = !empty($uInfo['avatar']) ? $uInfo['avatar']:'';
                $list[$k]['introduction'] = !empty($uInfo['introduction']) ? $uInfo['introduction']:'';
            }else{
                $list[$k]['nickname'] ='';
                $list[$k]['avatar'] ='';
                $list[$k]['introduction'] ='';
            }

        }

        $result = array("total" => $total, "rows" => $list);
        $this->success(__('读取成功'), $result,200);
    }

    /*
    * $tlist 获取的价格数组
    * 最大值与最小值
    */
    static public function max_min($tlist){
        if(empty($tlist))
            return false;
        $m = [];
        foreach($tlist as $v){
            $m[] = $v['price'];
        }

        $max = max($m);
        $min = min($m);
        unset($m);
        $data['max'] = $max;
        $data['min'] = $min;
        //$price = $min.'--'.$max;
        return $data;
    }
    /*
     * 活动收藏操作
     */
    public function operate(){
        $uInfo = $this->auth->getUserInfo();
        if(empty($uInfo)){//未登录
            $this->error(__('Please login first'), null, 401);
        }
        $admin_id = Iden::decrypt($uInfo['id']);
        if(empty($admin_id)){
            $this->error(__('获取用户参数出错'));
        }
       // $admin_id = 31896;
        $activity_id = $this->request->param('id');//活动id

        if(empty($activity_id)){
            $this->error('没有获取到活动id,请重试');
        }
        $aid = Iden::decrypt($activity_id);
        if(empty($aid)){
            $this->error('参数出错');
        }
        $ctype = $this->request->param('ctype');//收藏类型 1收藏 2 取消收藏

        if(empty($ctype)){
            $this->error('获取收藏类型出错');
        }
        if(!in_array($ctype,[1,2])){
            $this->error('获取收藏类型值有误,请重试');
        }

        try{
            if($ctype == 1){//收藏
                $row = $this->model->get(['uid' => $admin_id,'activity_id'=>$aid]);

                if ($row) {
                    $this->error('此活动您已收藏','',0 );
                }

                $data['activity_id'] = $aid;
                $data['uid'] = $admin_id;
                $data['ctime'] = time();
                $data['utime'] = time();
                $collect =  new ActivityCollect();
                $r = $collect->save($data);
                if (!$r){
                    $this->error('收藏失败，请重试', '', 0);
                }
                Db::table('activity')->where('id', $aid)->setInc('collect_cnt');//每收藏一次增1
                unset($data);
            }else{//取消收藏
                $row = $this->model->get(['uid' => $admin_id,'activity_id'=>$aid]);
                if (!$row) {
                    $this->error('没有找到此收藏活动','',0 );
                }

                $r = $this->model->where(['uid' => $admin_id,'activity_id'=>$aid])->delete();
                if(!$r){
                    $this->error('取消收藏失败，请重试', '', 0);
                }
                Db::table('activity')->where('id', $aid)->setDec('collect_cnt');//每取消收藏一次减1
            }

        }catch (\Exception $e){

            $this->error($e->getMessage());
        }
        $this->success(__('Operate successful'), '',200);
    }


}
